import { defineStore } from "pinia";
import { prefix, getCurrentPage } from "@/infrastructure/utils/common";
import userApi from "../../api/modules/user";
import { byUrlWorkCb } from "@/infrastructure/utils/is-tabbar-page.js";

// const userApi = {}
export default defineStore("user", {
  state: () => {
    return {
      // isLogin: false,
      userinfo: null,
      loginUserInfo: {},
      isShowLoginModal: false, //是否显示登录模态框
    };
  },
  actions: {
    ...userApi,
    // 解析code
    parseCode(data) {
      return userApi.parseCode(data);
    },
    register(data) {
      return userApi.register(data).then(
        (response) => {
          if (response.data.token) {
            localStorage.setItem(prefix, this.token);
          }
          uni.showToast({
            icon: "success",
            title: "注册成功",
          });
          return response;
        },
        () => {
          console.log("err");
        }
      );
    },
    login(data) {
      return userApi.login(data).then((response) => {
        if (response.data.token) {
          uni.setStorageSync(prefix, response.data.token);
          uni.setStorageSync("isLogin", true);
          uni.setStorageSync("userInfo", response.data);
          uni.setTabBarItem({
            index: 3,
            text: response.data.block_no,
          });
          const userList = uni.getStorageSync("userList");
          if (userList?.length) {
            let userindex = userList.findIndex(
              (items) => items.block_no == response.data.block_no
            );
            if (userindex == -1) { 
              console.log('新帐号')
              uni.setStorageSync("userList", [response.data,...userList]);
            } else {
              console.log('老帐号')
              userList[userindex] = response.data;
              uni.setStorageSync("userList", userList);
            }
          } else {
            uni.setStorageSync("userList", [response.data]);
          }
          // 开启是否有消息轮询
          byUrlWorkCb(
            getCurrentPage()?.route,
            uni.$store.settimereqStore.ecologySetTimeReqFn,
            uni.$store.settimereqStore.ecologyClearTimeReqFn
          );
          byUrlWorkCb(
            getCurrentPage()?.route,
            uni.$store.settimereqStore.mineSetTimeReqFn,
            uni.$store.settimereqStore.mineClearTimeReqFn
          );
          console.log(userList, "userList====");
        }
        uni.showToast({
          icon: "success",
          title: "登录成功",
        });
        return response;
      });
    },
    async getUserInfo() {
      // 切换地区调用这个
      const token = uni.getStorageSync(prefix);
      let res = await userApi.getUserInfo({ token });
      this.userinfo = res.data;
      uni.setStorageSync("isLogin", true);
      console.log(res.data, "userInforettt", this.userinfo);
    },
    async getLoginUserInfo() {
      // 切换地区调用这个
      const token = uni.getStorageSync(prefix);
      if (!token) {
        // this.logout()
        return;
      }
      let res = await userApi.getLoginUserInfo();
     
      if (!res || !res.data) {
        // this.logout()
      } else {
        this.loginUserInfo = res.data;
        console.log(this.loginUserInfo,'loginUserInfo')
        uni.setTabBarItem({
          index: 3,
          text: res.data.block_no,
        });
        console.log(res.data, "loginUserInforettt", this.loginUserInfo);
      }
    },
    clearUserInfo() {
      uni.setStorageSync("isLogin", false);
      uni.removeStorageSync("userInfo");
      // 切换地区调用这个
      this.userinfo = {};
      this.loginUserInfo = {};
    },
    async logout(flga=true) {
      const res = await userApi.logout();
      this.userinfo = null;
      this.loginUserInfo = {};
      // 存储用户信息数组中剔除当前账号信息
      const userList = uni.getStorageSync("userList") || [];
      const userInfo = uni.getStorageSync("userInfo");
      const newUserList = userList.filter((item) => {
        return item.block_no != userInfo.block_no;
      });
      uni.setStorageSync("userList", newUserList);
      uni.setStorageSync("isLogin", false);
      uni.removeStorageSync("userInfo");
      localStorage.removeItem(prefix);
      if(flga){
        uni.showToast({
          icon: "success",
          title: "退出成功",
        });
      }
    
    },

    compelledlogout() {
      // 被挤掉了清除list
      const userList = uni.getStorageSync("userList") || [];
      const userInfo = uni.getStorageSync("userInfo");
      const newUserList = userList.filter((item) => {
        return item.block_no != userInfo.block_no;
      });
      uni.setStorageSync("userList", newUserList);
      uni.setStorageSync("isLogin", false);
      uni.removeStorageSync("userInfo");
      localStorage.removeItem(prefix)
      this.userinfo = null;
      this.loginUserInfo = {};
      uni.setTabBarItem({
        index: 3,
        text: '游客',
      });
    },

  },
});
